import { v4 as uuidv4 } from 'uuid';

// 定义服务类型
export enum AgentServiceType {
  ADVISOR = 'finpilot_agent_service',
  DOC_ANALYSIS = 'doc_analysis_agent_service',
  ASSISTANT = 'credit_flow_assist_service_v2',
  B2B = 'credit_flow_assist_service'
}

export interface StreamMessage {
  id: string;
  text: string;
  role: 'user' | 'agent';
  status: 'sending' | 'sent' | 'error';
  timestamp: number;
  contentType?: 'text' | 'markdown';
  metadata?: {
    processingTime?: number;
    serviceId?: string;
    isStreamed?: boolean;
    firstTokenTime?: number; // 首Token时间延迟(秒)
    totalDelta?: number; // 总处理时间延迟(秒)
  };
}

export interface StreamBody {
  type: 'start' | 'task_start' | 'planning_start' | 'sub_task_progress' | 'llm_output' | 'json_block' | 'llm_end' | 'task_complete' | 'task_progress' ;
  data: {
    content?: string;
    result?: string;
    message?: string;
    progress?: string;
    agent_name?: string;
    query?: string;
    task_count?: number;
    duration?: number;
    analysis_item?: string;
    [key: string]: any; // 允许其他字段
  }
}

interface StreamApiConfig {
  baseURL?: string;
  serviceRunPath?: string;
}

class StreamApiService {
  private currentService: string = AgentServiceType.ADVISOR;
  private sessionId: string = '';
  private currentController: AbortController | null = null;
  private config: StreamApiConfig = {};

  setConfigParams(config: StreamApiConfig = {}) {
    this.sessionId = uuidv4();
    this.config = {
      baseURL: config.baseURL || '/langchain-backend',
      serviceRunPath: config.serviceRunPath || '/service_run_stream'
    };
  }

  // 设置服务类型
  setServiceType(serviceType: string): void {
    this.currentService = serviceType;
  }

  // 获取当前服务类型
  getCurrentService(): string {
    return this.currentService;
  }

  // 发送消息到智能体（流式响应）
  async sendMessageStream(
    message: string,
    onChunk: (chunk: string, accumulated: string, phase?: 'reasoning' | 'llm', messageType?: string) => void,
    onComplete: (fullMessage: StreamMessage) => void,
    onError: (error: string) => void,
    userName?: string,
    sessionId?: string,
    docIds?: string[], // 文档ID列表
    framework?:any,
    chat_from?:string,
    config?: Partial<StreamApiConfig>, // 动态配置
  ): Promise<void> {
    const startTime = Date.now();
    const messageId = Date.now().toString();
    let accumulatedText = '';
    let firstTokenTime: number | undefined = undefined; // 记录首Token时间
    let endTime: number | undefined = undefined; // 记录结束时间

    try {
      // 创建AbortController用于终止请求
      this.currentController = new AbortController();

      // 获取基础URL
      const baseURL = config?.baseURL || this.config.baseURL;
      // 构建请求参数
      let requestParams: any = {
        input: message,
        background: '',
        session_id: sessionId || this.sessionId,
        user_name: userName
      };

      // 如果有docIds，添加到请求参数中
      if (docIds && docIds.length > 0) {
        requestParams.docIds = docIds;
      }
      requestParams.chat_from = chat_from;
      // 调用流式API
      const response = await fetch(`${baseURL}${this.config.serviceRunPath}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(this.config.serviceRunPath !='/service_run_stream'? {
          input: message,
          framework: framework,
        } :{
          service_id: 'financial_analyze_reports_agent',
          params: requestParams,
          chat_from:chat_from
        }),
        signal: this.currentController.signal
      });

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }

      if (!response.body) {
        throw new Error('响应体为空');
      }

      const reader = response.body.getReader();
      const decoder = new TextDecoder();

      while (true) {
        const { done, value } = await reader.read();

        if (done) {
          break;
        }

        const chunk = decoder.decode(value, { stream: true });
        const lines = chunk.split('\n');

        for (const line of lines) {
          if (line.trim() === '') continue;

          // 处理SSE格式数据
          if (line.startsWith('data:')) {
            const dataStr = line.slice(5).trim();

            if (dataStr === '[DONE]') {
              break;
            }

            try {
              const data = JSON.parse(dataStr) as StreamBody;
              const type = data.type;

              // 检查是否为完成状态
              if (type === 'task_complete') {
                endTime = Date.now();
              }
              // 记录首Token时间
              // 根据实际API格式解析数据
              let chunkText = '';
              if (type === 'llm_output' && data.data.content) {
                // 记录首Token时间
                if (!firstTokenTime) {
                  firstTokenTime = Date.now();
                }
                chunkText = data.data.content;
              }
              if(type == 'task_start' || type == 'planning_start' || type == 'sub_task_progress' || type == 'task_progress') {
                // 根据API返回的数据结构提取内容
                chunkText = data.data.message ||
                           data.data.content ||
                           data.data.progress ||
                           ``;
              }
              if (chunkText) {
                // 对于进度类消息，不累积到accumulatedText中，避免干扰最终的回复内容
                if (type === 'llm_output') {
                  accumulatedText += chunkText;
                }
                console.log('🚀 调用onChunk:', { type, chunkText, accumulatedLength: accumulatedText.length });
                // 传递消息类型参数
                if (type === 'llm_output') {
                  onChunk(chunkText, accumulatedText, 'llm', type);
                } else if (type === 'task_start' || type === 'planning_start' || type === 'sub_task_progress' || type === 'task_progress') {
                  onChunk(chunkText, accumulatedText, 'reasoning', type);
                } else {
                  onChunk(chunkText, accumulatedText, undefined, type);
                }
              }
            } catch (e) {
              console.warn('解析流式数据失败:', e, dataStr);
              // 如果不是JSON格式，检查是否是有效的文本内容
              if (dataStr && dataStr !== '[DONE]' && !dataStr.startsWith('{') && !dataStr.startsWith('[')) {
                // 只有当数据不是JSON格式时才作为文本处理
                accumulatedText += dataStr;
                onChunk(dataStr, accumulatedText, undefined, 'text');
              }
            }
          }
        }
      }

      const processingTime = Date.now() - startTime;

      // 清理累积文本，移除可能的JSON格式数据
      let cleanedText = accumulatedText || '抱歉，我暂时无法理解您的问题，请换个方式问我。';

      // 检查并清理JSON格式数据
      if (typeof cleanedText === 'string' &&
          (cleanedText.includes('{"result":') || cleanedText.includes('{"chat_history":'))) {
        // 如果检测到JSON格式数据，尝试清理
        try {
          const jsonMatch = cleanedText.match(/^(.*?)(\{.*\})$/s);
          if (jsonMatch) {
            cleanedText = jsonMatch[1].trim() || '抱歉，我暂时无法理解您的问题，请换个方式问我。';
          }
        } catch {
          cleanedText = '抱歉，我暂时无法理解您的问题，请换个方式问我。';
        }
      }

      // 计算时间延迟（转换为秒）
      const firstTokenDelta = firstTokenTime ? (firstTokenTime - startTime) / 1000 : undefined;
      const totalDelta = endTime ? (endTime - startTime) / 1000 : undefined;

      // 创建完整的消息对象
      const fullMessage: StreamMessage = {
        id: messageId,
        text: cleanedText,
        role: 'agent',
        status: 'sent',
        timestamp: Date.now(),
        contentType: 'markdown',
        metadata: {
          processingTime,
          serviceId: this.currentService,
          isStreamed: true,
          firstTokenTime: firstTokenDelta, // 首Token延迟(秒)
          totalDelta: totalDelta, // 总处理时间(秒)
        },
      };

      onComplete(fullMessage);

    } catch (error) {
      // 检查是否是因为手动终止导致的错误
      if (error instanceof Error && error.name === 'AbortError') {
        console.log('流式请求被手动终止');
        return; // 不调用onError，因为这是预期的行为
      }

      console.error('流式API调用失败:', error);
      onError(error instanceof Error ? error.message : '流式连接失败，请检查网络连接');
    } finally {
      this.currentController = null;
    }
  }

  // 终止当前的流式请求
  stopStream(): void {
    if (this.currentController) {
      this.currentController.abort();
      this.currentController = null;
    }
  }

  // 获取sessionId
  getSessionId(): string {
    return this.sessionId;
  }


}

export const streamApiService = new StreamApiService();
